<template>
  <div class="search">
    <Row>
      <Col>
        <Card>
          <Row class="operation">
            <Form inline :label-width="170" ref="form" :model="form" label-position="right">
              <Button @click="getDataList" icon="md-refresh">刷新</Button>
              <Button @click="add" type="primary" icon="md-add">添加</Button>
              <FormItem label="是否过期" prop="pastDue">
                <Select v-model="searchForm.pastDue" clearable style="width:200%">
                  <!-- <Option value="">全部</Option> -->
                  <Option value="YES">已过期</Option>
                  <Option value="NO">未过期</Option>
                </Select>
              </FormItem>
              <Button @click="handleSearch" type="primary" icon="ios-search" style="margin-left:90px;">搜索</Button>
            </Form>
          </Row>
          
          <Row>
            <Table :loading="loading" border :columns="columns" :data="data" ref="table" sortable="custom" @on-sort-change="changeSort"></Table>
          </Row>
          <Row type="flex" justify="end" class="page">
            <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
          </Row>
        </Card>
      </Col>
    </Row>
    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="700">
      <Form ref="form" :model="form" :label-width="100" :rules="formValidate" >
        <FormItem label="优惠券名称" prop="title">
          <Input v-model="form.title" style="width:100%" placeholder="请输入优惠券名称"/>
        </FormItem>
        <Form-item label="优惠券类型" prop="disCouponType">
          <Select v-model="form.disCouponType" style="width:100%" @on-change="changeType">
            <Option value="ALL_USE">全店通用</Option>
            <Option value="ONE_PRODUCT">商品满减</Option>
          </Select>
        </Form-item>
        <Form-item label="场地列表" prop="goodsPackageId" v-if="couponType === 'ONE_PRODUCT' && service =='婚宴酒店'">
          <Select v-model="form.goodsPackageId" style="width:100%" filterable>
            <Option :value="item.id" v-for="(item,index) in goodsData" :key="index">{{item.siteName}}</Option>
          </Select>
        </Form-item>
        <Form-item label="商品列表" prop="goodsPackageId" v-if="couponType === 'ONE_PRODUCT' && service !='婚宴酒店'">
          <Select v-model="form.goodsPackageId" style="width:100%" filterable>
            <Option :value="item.id" v-for="(item,index) in goodsData" :key="index">{{item.goodName}}</Option>
          </Select>
        </Form-item>
        <FormItem label="满多少" prop="fullMoney">
          <Input v-model="form.fullMoney" style="width:100%" placeholder="请输入满多少金额"/>
        </FormItem>
        <FormItem label="减多少" prop="subtractMoney">
          <Input v-model="form.subtractMoney" style="width:100%" placeholder="请输入减多少金额"/>
        </FormItem>
        <FormItem label="有效期" prop="validityPeriod">
          <Date-picker type="datetime" placeholder="选择有效截止时间" style="width: 100%" format="yyyy-MM-dd 23:59:59" @on-change="changeTime" :value="form.validityPeriod" :options="options3"></Date-picker>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="modalVisible=false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
      </div>
    </Modal>
    
  </div>
</template>

<script>
import { validateName } from "@/libs/validate";
import {
  getUserListData, userInfo
} from "@/api/index";
import circleLoading from "@/views/my-components/circle-loading.vue";
export default {
  name: "staffManagement",
  components: {
    circleLoading,
  },
  data() {
    return {
      options3: {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      timeValue: "",
      loading: true, // 表单加载状态
      loadingEdit: false,
      modalType: 0, // 添加或编辑标识
      modalVisible: false, // 添加或编辑显示
      modalTitle: "", // 添加或编辑标题
      searchForm: { // 搜索框初始化对象
        pageNumber: 1, // 当前页数
        pageSize: 10, // 页面大小
        pastDue: "",
      },
      form: { // 添加或编辑表单对象初始化数据
        title: "",
        disCouponType: "",
        goodsPackageId: "",
        fullMoney: "",
        subtractMoney: "",
        validityPeriod: ""
      },
      selectData:[],
      // 表单验证规则
      formValidate: {
        disCouponType: [{ required: true, message: "请选择优惠券类型", trigger: "change" }],
        goodsPackageId: [{ required: true, message: "请选择商品", trigger: "change" }],
        fullMoney: [{ required: true, message: "请输入满多少金额", trigger: "blur", pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/ }],
        subtractMoney: [{ required: true, message: "请输入减多少金额", trigger: "blur", pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/ }],
        title: [{ required: true, message: "请输入优惠券标题", trigger: "blur" },
          { validator: validateName, trigger: "blur" },],
        validityPeriod: [{ required: true, message: "请选择有效日期", trigger: "change" }],
      },
      submitLoading: false, // 添加或编辑提交状态
      columns: [
        // 表头
        {
          type: "index",
          width: 60,
          align: "center"
        },
        {
          title: "优惠券名称",
          key: "title",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "类型",
          key: "disCouponType",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "商品名称",
          key: "goodsName",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "满多少",
          key: "fullMoney",
          minWidth: 90,
          sortable: false,
        },
        {
          title: "减多少",
          key: "subtractMoney",
          minWidth: 90,
          sortable: false,
        },
        {
          title: "是否过期",
          key: "pastDue",
          minWidth: 90,
          sortable: false,
        },
        {
          title: "截止有效期",
          key: "validityPeriod",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "创建时间",
          key: "createTime",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          fixed: "right",
          minWidth: 120,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                    icon: "md-trash"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row);
                    }
                  }
                },
                "删除"
              ),
            ]);
          }
        }
      ],
      data: [], // 表单数据
      total: 0, // 表单数据总数
      couponType: "",
      goodsData: [],
      service: "",
    };
  },
  methods: {
    init() {
      this.service = JSON.parse(this.getStore("userInfo")).serviceCategoryName;
      this.getDataList();
      this.getGoodsList();
      
      // this.service = str;
    },
    changeType (e) {
      console.log(e)
      this.couponType = e;
    },
    changeTime (e) {
      console.log(e);
      this.form.validityPeriod = e;
    },
    handleSearch () {
      if (this.searchForm.pastDue === undefined) {
        this.searchForm.pastDue = "";
      }
      this.searchForm.pageNumber = 1;
      this.getDataList()
    },
    getGoodsList () {
      console.log(this.service)
      if (this.service === "婚宴酒店") {
        var data = {
          storeId: JSON.parse(this.getStore("userInfo")).id
        }
        this.postRequest("/site/getSiteList", data).then(res=> {
        if (res.success) {
            this.goodsData = res.result
          } else {
            this.goodsData = []
          }
        })
      } else {
        var data = {
          pageNumber: 1,
          pageSize: 1000
        }
        this.postRequest("/good/PCgoodsList", data).then(res=> {
        if (res.success) {
            this.goodsData = res.result.data
          } else {
            this.goodsData = []
          }
        })
      } 
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getDataList();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getDataList();
    },
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      // 重新加载数据
      this.getDataList();
    },
    changeSort(e) {
      this.searchForm.sort = e.key;
      this.searchForm.order = e.order;
      if (e.order === "normal") {
        this.searchForm.order = "";
      }
      this.getDataList();
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
      this.searchForm.advertisingType=''
      this.searchForm.advertisingJumpType=''
    },
    getDataList() {
        if (this.searchForm.pastDue == undefined) {
            this.searchForm.pastDue = ""
        }
        this.loading = true;
        // 带多条件搜索参数获取表单数据 请自行修改接口
        this.postRequest("/discountCoupon/PcGetDiscountCouponList", this.searchForm).then(res => {
            this.loading = false;
            if (res.success) {
              this.data = res.result.data;
              this.total = res.result.size;
            } else if (res.code == 201) {
              this.data=[];
              this.total=0;
            }
        });
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          if (this.modalType === 0) {
            // 添加 避免编辑后传入id等数据 记得删除
            delete this.form.id;
            this.postRequest("/discountCoupon/insertOrderUpdateDiscountCoupon", this.form).then(res => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.getDataList();
                this.modalVisible = false;
              }
            });
          }
        }
      });
    },
    add() {
      this.timeValue = "";
      this.modalType = 0;
      this.modalTitle = "添加";
      this.$refs.form.resetFields();
      this.form.validityPeriod = ""
      delete this.form.id;
      this.modalVisible = true;
    },
    edit(v) {
      this.modalType = 1;
      this.modalTitle = "编辑";
      this.$refs.form.resetFields();
      // 转换null为""
      for (let attr in v) {
        if (v[attr] === null) {
          v[attr] = "";
        }
      }
      let str = JSON.stringify(v);
      let data = JSON.parse(str);
      this.advertType = data.advertisingJumpType;
      this.form = data;
      delete this.form._index;
      delete this.form._rowKey;
      console.log(this.form)
      this.modalVisible = true;
    },
    remove(v){
      this.$Modal.confirm({
        title: "确认删除",
        // 记得确认修改此处
        content: "您确认要删除?",
        loading: true,
        onOk: () => {
          var param={
            ids:v.id
          }
          this.postRequest("/discountCoupon/removeDiscountCoupon",param).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.getDataList();
            }
          });
        }
      });
    },
    delAll() {
        console.log(this.data)
        if (this.selectCount <= 0) {
            this.$Message.warning("您还未选择要删除的数据");
            return;
        }
        this.$Modal.confirm({
            title: "确认删除",
            content: "您确认要删除所选的数据?",
            loading: true,
            onOk: () => {
            // 批量删除
                this.postRequest("/size/removeSize",{id:this.brandId}).then(res => {
                    this.$Modal.remove();
                    if (res.success) {
                        this.$Message.success("操作成功");
                        this.clearSelectAll();
                        this.getDataList();
                    }
                })
            // 模拟请求成功
                this.$Message.success("操作成功");
                this.$Modal.remove();
                this.clearSelectAll();
                this.getDataList();
            }
        })
    }
  },
  mounted() {
    this.init();
  }
};
</script>
<style lang="less">
.search {
    .operation {
        margin-bottom: 2vh;
    }
    .select-count {
        font-size: 13px;
        font-weight: 600;  
        color: #40a9ff;
    }
    .select-clear {
        margin-left: 10px;
    }
    .page {
        margin-top: 2vh;
    }
    .drop-down {
        font-size: 13px;
        margin-left: 5px;
    }
}
</style>